package com.treasure.service.sms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.submail.utils.RequestEncoder;
import com.treasure.service.commons.lang.util.StringUtil;
import com.treasure.service.constant.Constants;
import com.treasure.service.enums.CodeEnum;
import com.treasure.service.enums.RedisKeys;
import com.treasure.service.enums.SmsTemplate;
import com.treasure.service.third.utils.RestClient;
import com.treasure.service.result.ResponseResult;
import com.treasure.service.sms.service.SmsService;
import com.treasure.service.commons.lang.util.ParserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

/**
* @Description:    java类作用描述
* @Author:         panxinwen
* @CreateDate:     2018/11/18 14:17
* @Version:        1.0
*/
@Service
public class SmsServiceImpl implements SmsService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private RestClient restClient;

    @Value("${submail.tenant.appid}")
    private String appid;

    @Value("${submail.tenant.appkey}")
    private String appkey;

    @Value("${submail.sendSms.url}")
    private String url;

    @Value("${submail.timestamp.url}")
    private String timestampUrl;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public ResponseResult sendSms(Integer smsType, String phonenumber) {

        String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);

        String content = ParserUtils.parse0(SmsTemplate.getTemplate(smsType),verifyCode);

        logger.info("发送短信手机号{},模板{}",phonenumber,content);

        String result = restClient.post(url,getParam(phonenumber,content),String.class);

        logger.info("发送短信返回手机号{},結果{}",phonenumber,result);

        JSONObject json = JSONObject.parseObject(result);

        if (json.getString("status").equals(Constants.SUCCESS)){
            //Todo 验证码放入缓存
            redisTemplate.opsForHash().put(RedisKeys.AUTH_CODE.build(phonenumber),smsType+"",verifyCode);
            redisTemplate.opsForHash().put(RedisKeys.AUTH_CODE.build(phonenumber),"A"+smsType,StringUtil.getNowTimeStamp());

            return new ResponseResult();
        }else {
            return new ResponseResult(CodeEnum.SMSFAIL,CodeEnum.SMSFAIL.getDesc(),null);
        }

    }

    @Override
    public ResponseResult sendSmsTemp(String temp, String phonenumber) {
        logger.info("发送短信手机号{},模板{}",phonenumber,temp);
        String result = restClient.post(url,getParam(phonenumber,temp),String.class);
        logger.info("发送短信返回手机号{},結果{}",phonenumber,result);
        JSONObject json = JSONObject.parseObject(result);
        if (json.getString("status").equals(Constants.SUCCESS)){

            return new ResponseResult();
        }else {
            return new ResponseResult(CodeEnum.SMSFAIL,CodeEnum.SMSFAIL.getDesc(),null);
        }

    }

    private String getTimestamp(){


        String jsonStr = restClient.get(timestampUrl,new HashMap<>(),String.class);
        if(jsonStr != null){
            JSONObject json = JSONObject.parseObject(jsonStr);
            return json.getString("timestamp");
        }

        return null;
    }

    private Map getParam(String phonenumber,String content){

        Map<String,Object> builder = new HashMap<>();
        TreeMap<String, Object> requestData = new TreeMap<String, Object>();
        requestData.put("appid", appid);
        requestData.put("content", content);
        requestData.put("to", phonenumber);

        for(Map.Entry<String, Object> entry: requestData.entrySet()){
            String key = entry.getKey();
            Object value = entry.getValue();
            if(value instanceof String){
                builder.put(key, String.valueOf(value));
            }
        }
        String timestamp = getTimestamp();
        requestData.put("timestamp", timestamp);
        requestData.put("sign_type", "md5");
        String signStr = appid + appkey + RequestEncoder.formatRequest(requestData) + appid + appkey;
        System.out.println(signStr);
        builder.put("timestamp", timestamp);
        builder.put("sign_type", "md5");
        try {
            builder.put("signature", RequestEncoder.encode("md5", signStr));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return builder;

    }

}
